// pages/myCommunity/myCommunity.js
const {
  getMyCommunity,
  outCommunity
} = require('../../services/myCommunityReq')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    pageNum: 1,
    pageSize: 10,
    isFinish: false
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.handleGetMyCommunity()
  },

  onLoad(options) {
    this.handleGetMyCommunity()
  },
  handleGetMyCommunity() {
    if (this.data.isFinish) {
      return
    }
    wx.showLoading({
      title: '加载中',
    })
    const id = wx.getStorageSync('volunteerInfo').volunteerId
    getMyCommunity(id, res => {
      console.log(res.data.data)
      let list = res.data.data
      if (list.length < this.data.pageSize) {
        this.setData({
          isFinish: true
        })
      }
      list.forEach(item => {
        try {
          item.info.communityAddress = JSON.parse(item.info.communityAddress)
          console.log(item)
        } catch (e) {}
      })
      this.setData({
        list: list,
        pageNum: this.data.pageNum + 1
      })
      wx.hideLoading({
        success: (res) => {},
      })
    })
  },

  // 跳转社团详情
  handleGoDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `../communityDetail/communityDetail?id=${id}`,
    })
  },

  // 退出社团
  handleOut(e) {
    const id = e.currentTarget.dataset.id
    wx.showModal({
      cancelColor: 'red',
      title: '确定要退出该社团吗？',
      success: res => {
        if (res.confirm) {
          // 执行退出操作
          outCommunity(id, res => {
            console.log(res)
            if (res.data.code !== 0) {
              wx.showToast({
                title: res.data.msg,
                icon: 'none'
              })
            } else {
              this.setData({
                pageNum: 1,
                isFinish: false
              })
              wx.showToast({
                title: '退出成功',
              })
              this.handleGetMyCommunity()
            }
          })
        } else {

        }
      }
    })
  }
})